package edu.sctu;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.datatransfer.DataFlavor;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by 星月 on 2018/6/11.
 */
public class AddUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //解决数据库中中文乱码问题
        request.setCharacterEncoding("utf-8");

        String username=request.getParameter("username");
        String password=request.getParameter("password");
        Connection connection=null;
        Statement statement=null;
        String sql="insert into t_users(username,password)values('"+username+"','"+password+"')";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("" +
                            "jdbc:mysql://localhost:3306/sctu_javaweb_2018?serverTimezone=UTC",
                    "root",
                    "123456");
            statement =connection.createStatement();
            statement.execute(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //解决中文乱码
        response.setCharacterEncoding("gbk");

        PrintWriter out=response.getWriter();
        out.write("<h1>成功添加用户！</h1>");
        out.write("<a href='userList.jsp'>返回首页</a>");
    }
}
